{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Agent Types"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. Intended Model Type 预期型号类型\n",
    "\n",
    "Whether this agent is intended for Chat Models (takes in messages, outputs message) or LLMs (takes in string, outputs string). The main thing this affects is the prompting strategy used. You can use an agent with a different type of model than it is intended for, but it likely won't produce results of the same quality.<br>\n",
    "此代理是用于聊天模型（接收消息，输出消息）还是 LLM（接收字符串，输出字符串）。这影响的主要因素是所使用的提示策略。您可以使用与预期类型不同的代理，但它可能不会产生相同质量的结果。\n",
    "\n",
    "2. Supports Chat History 支持聊天记录\n",
    "\n",
    "Whether or not these agent types support chat history. If it does, that means it can be used as a chatbot. If it does not, then that means it's more suited for single tasks. Supporting chat history generally requires better models, so earlier agent types aimed at worse models may not support it.<br>\n",
    "这些座席类型是否支持聊天记录。如果是这样，这意味着它可以用作聊天机器人。如果没有，那么这意味着它更适合单一任务。支持聊天记录通常需要更好的模型，因此针对较差模型的早期代理类型可能不支持它。\n",
    "\n",
    "3. Supports Multi-Input Tools 支持多路输入工具\n",
    "\n",
    "Whether or not these agent types support tools with multiple inputs. If a tool only requires a single input, it is generally easier for an LLM to know how to invoke it. Therefore, several earlier agent types aimed at worse models may not support them.<br>\n",
    "这些代理类型是否支持具有多个输入的工具。如果一个工具只需要一个输入，那么LLM通常更容易知道如何调用它。因此，针对较差模型的几种早期代理类型可能不支持它们。\n",
    "\n",
    "4. Supports Parallel Function Calling 支持并行函数调用\n",
    "\n",
    "Having an LLM call multiple tools at the same time can greatly speed up agents whether there are tasks that are assisted by doing so. However, it is much more challenging for LLMs to do this, so some agent types do not support this.<br>\n",
    "让 LLM 同时调用多个工具可以大大加快座席的速度，无论是否有通过这样做来辅助的任务。但是，对于 LLM 来说，执行此操作更具挑战性，因此某些代理类型不支持此功能。\n",
    "\n",
    "5. Required Model Params 必需的模型参数\n",
    "\n",
    "Whether this agent requires the model to support any additional parameters. Some agent types take advantage of things like OpenAI function calling, which require other model parameters. If none are required, then that means that everything is done via prompting<br>\n",
    "此代理是否要求模型支持任何其他参数。某些代理类型利用了 OpenAI 函数调用等功能，这些功能需要其他模型参数。如果不需要，则意味着一切都是通过提示完成的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"TAVILY_API_KEY\"] = \"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\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## ReAct"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m LangChain is probably a term or concept that I'm not familiar with.\n",
      "Action: tavily_search_results_json\n",
      "Action Input: LangChain\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://www.langchain.com/', 'content': 'Join Discord\\nContribute on GitHub\\n5.3M\\nMonthly Downloads\\n67k\\nGithub Stars\\n1800+\\nContributors\\n34k+\\nApps Powered\\nReady to build?\\nGo To Docs\\nGo To Docs\\nGo To Docs\\nContact Sales\\nContact Sales\\nContact Sales\\nProducts and use-cases\\nLangChain\\nLangSmith\\nRetrieval\\nAgents\\nInspiration\\nCode\\nGitHub\\nLangChain Hub\\nPython Docs\\nJS/TS Docs\\nSocial\\nTwitter\\nDiscord\\nBlog\\nLinkedIn\\nYouTube\\nTerms of Service\\nSign up for our newsletter\\nProducts and use-cases\\nLangChain\\nLangSmith\\nRetrieval\\nAgents\\nInspiration\\nCode\\nGitHub\\nLangChain Hub\\nPython Docs\\nJS/TS Docs\\nSocial\\nTwitter\\nDiscord\\nBlog\\nLinkedIn\\nYouTube\\nTerms of Service\\nSign up for our newsletter\\nProducts and use-cases\\nLangChain\\nLangSmith\\nRetrieval\\nAgents\\nInspiration\\nCode\\nGitHub\\nLangChain Hub\\nPython Docs\\nJS/TS Docs\\nSocial\\nTwitter\\nDiscord\\nBlog\\nLinkedIn\\nYouTube\\nTerms of Service\\nSign up for our newsletter Chatbots\\nQ&A Over Docs\\nSummarization\\nCopilots\\nWorkflow Automation\\nDocument Analysis\\nCustom Search\\nHarness the power–and wrangle the complexity– of LLMs\\nGet from proof-of-concept to production on one platform\\nRely on a set of tools built especially for non-deterministic models\\nLeverage new cognitive architectures and battle-tested orchestration\\nThanks to our contributors and partners for making LangChain awesome\\nWhen you build with LangChain, you build alongside a community of developers advancing the frontier of what’s possible with LLMs.\\n 🦜🔗 LangChain\\nLangSmith\\nLangServe\\nAgents\\nRetrieval\\nEvaluation\\nBlog\\nDocs\\n🦜🔗 LangChain\\n🦜🔗 LangChain\\nLangChain Expression Language makes it easy to create custom chains.\\n Go To Docs\\nGo To Docs\\nGo To Docs\\nContact Sales\\nglobal corporations, STARTUPS, and TINKERERS build with LangChain\\nglobal corporations, STARTUPS, and TINKERERS build with LangChain\\nglobal corporations, STARTUPS, and TINKERERS build with LangChain\\nA complete set of powerful building blocks\\nA complete set of powerful building blocks\\n Try it out here\\nGet your LLM application from prototype to production\\nGet your LLM application from prototype to production\\nBuild context-aware, reasoning applications with LangChain’s flexible abstractions and AI-first toolkit.\\n'}]\u001b[0m\u001b[32;1m\u001b[1;3mThe search engine has provided me with a lot of information about LangChain. I should read through it and try to understand what it is.\n",
      "Action: Read through the search results\n",
      "Action Input: LangChain\u001b[0mRead through the search results is not a valid tool, try one of [tavily_search_results_json].\u001b[32;1m\u001b[1;3mI should use the tavily_search_results_json tool to read through the search results for LangChain.\n",
      "Action: tavily_search_results_json\n",
      "Action Input: LangChain\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://www.langchain.com/', 'content': 'Join Discord\\nContribute on GitHub\\n5.3M\\nMonthly Downloads\\n67k\\nGithub Stars\\n1800+\\nContributors\\n34k+\\nApps Powered\\nReady to build?\\nGo To Docs\\nGo To Docs\\nGo To Docs\\nContact Sales\\nContact Sales\\nContact Sales\\nProducts and use-cases\\nLangChain\\nLangSmith\\nRetrieval\\nAgents\\nInspiration\\nCode\\nGitHub\\nLangChain Hub\\nPython Docs\\nJS/TS Docs\\nSocial\\nTwitter\\nDiscord\\nBlog\\nLinkedIn\\nYouTube\\nTerms of Service\\nSign up for our newsletter\\nProducts and use-cases\\nLangChain\\nLangSmith\\nRetrieval\\nAgents\\nInspiration\\nCode\\nGitHub\\nLangChain Hub\\nPython Docs\\nJS/TS Docs\\nSocial\\nTwitter\\nDiscord\\nBlog\\nLinkedIn\\nYouTube\\nTerms of Service\\nSign up for our newsletter\\nProducts and use-cases\\nLangChain\\nLangSmith\\nRetrieval\\nAgents\\nInspiration\\nCode\\nGitHub\\nLangChain Hub\\nPython Docs\\nJS/TS Docs\\nSocial\\nTwitter\\nDiscord\\nBlog\\nLinkedIn\\nYouTube\\nTerms of Service\\nSign up for our newsletter Chatbots\\nQ&A Over Docs\\nSummarization\\nCopilots\\nWorkflow Automation\\nDocument Analysis\\nCustom Search\\nHarness the power–and wrangle the complexity– of LLMs\\nGet from proof-of-concept to production on one platform\\nRely on a set of tools built especially for non-deterministic models\\nLeverage new cognitive architectures and battle-tested orchestration\\nThanks to our contributors and partners for making LangChain awesome\\nWhen you build with LangChain, you build alongside a community of developers advancing the frontier of what’s possible with LLMs.\\n 🦜🔗 LangChain\\nLangSmith\\nLangServe\\nAgents\\nRetrieval\\nEvaluation\\nBlog\\nDocs\\n🦜🔗 LangChain\\n🦜🔗 LangChain\\nLangChain Expression Language makes it easy to create custom chains.\\n Go To Docs\\nGo To Docs\\nGo To Docs\\nContact Sales\\nglobal corporations, STARTUPS, and TINKERERS build with LangChain\\nglobal corporations, STARTUPS, and TINKERERS build with LangChain\\nglobal corporations, STARTUPS, and TINKERERS build with LangChain\\nA complete set of powerful building blocks\\nA complete set of powerful building blocks\\n Try it out here\\nGet your LLM application from prototype to production\\nGet your LLM application from prototype to production\\nBuild context-aware, reasoning applications with LangChain’s flexible abstractions and AI-first toolkit.\\n'}]\u001b[0m\u001b[32;1m\u001b[1;3m I now know a lot more about LangChain and its capabilities.\n",
      "Final Answer: LangChain is a platform for building context-aware, reasoning applications using LLMs. It has a set of powerful building blocks and a community of developers working on advancing the frontier of what's possible with LLMs.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'what is LangChain?',\n",
       " 'output': \"LangChain is a platform for building context-aware, reasoning applications using LLMs. It has a set of powerful building blocks and a community of developers working on advancing the frontier of what's possible with LLMs.\"}"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, create_react_agent\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_openai import OpenAI\n",
    "\n",
    "tools = [TavilySearchResults(max_results=1)]\n",
    "# Choose the LLM to use\n",
    "llm = OpenAI()\n",
    "\n",
    "# Get the prompt to use - you can modify this!\n",
    "prompt = hub.pull(\"hwchase17/react\")\n",
    "\n",
    "# Construct the ReAct agent\n",
    "agent = create_react_agent(llm, tools, prompt)\n",
    "# Create an agent executor by passing in the agent and tools\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)\n",
    "# \n",
    "agent_executor.invoke({\"input\": \"what is LangChain?\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mThought: Do I need to use a tool? No\n",
      "Final Answer: Your name is Bob.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': \"what's my name? Only use a tool if needed, otherwise respond with Final Answer\",\n",
       " 'chat_history': 'Human: Hi! My name is Bob\\nAI: Hello Bob! Nice to meet you',\n",
       " 'output': 'Your name is Bob.'}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Get the prompt to use - you can modify this!\n",
    "prompt = hub.pull(\"hwchase17/react-chat\")\n",
    "# Construct the ReAct agent\n",
    "agent = create_react_agent(llm, tools, prompt)\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)\n",
    "# \n",
    "agent_executor.invoke(\n",
    "    {\n",
    "        \"input\": \"what's my name? Only use a tool if needed, otherwise respond with Final Answer\",\n",
    "        # Notice that chat_history is a string, since this prompt is aimed at LLMs, not chat models\n",
    "        \"chat_history\": \"Human: Hi! My name is Bob\\nAI: Hello Bob! Nice to meet you\",\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Self-ask with search"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mYes.  \n",
      "Follow up: Who is the reigning men's U.S. Open champion?  \u001b[0m\u001b[36;1m\u001b[1;3mCarlos Alcaraz is the reigning men's U.S. Open champion, having won the title on September 11, 2022, by defeating Casper Ruud in four sets.\u001b[0m\u001b[32;1m\u001b[1;3mFollow up: Where is Carlos Alcaraz from?  \u001b[0m\u001b[36;1m\u001b[1;3mCarlos Alcaraz is from Spain, as he is coached by Spanish tennis player Juan Carlos Ferrero and has a strong connection to the country's national team celebrations.\u001b[0m\u001b[32;1m\u001b[1;3mSo the final answer is: Spain\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': \"What is the hometown of the reigning men's U.S. Open champion?\",\n",
       " 'output': 'Spain'}"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, create_self_ask_with_search_agent\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_community.tools.tavily_search import TavilyAnswer\n",
    "\n",
    "\n",
    "tools = [TavilyAnswer(max_results=1, name=\"Intermediate Answer\")]\n",
    "# Get the prompt to use - you can modify this!\n",
    "prompt = hub.pull(\"hwchase17/self-ask-with-search\")\n",
    "# Choose the LLM that will drive the agent\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# Construct the Self Ask With Search Agent\n",
    "agent = create_self_ask_with_search_agent(llm, tools, prompt)\n",
    "\n",
    "# Create an agent executor by passing in the agent and tools\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)\n",
    "\n",
    "agent_executor.invoke(\n",
    "    {\"input\": \"What is the hometown of the reigning men's U.S. Open champion?\"}\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Structured chat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mThought: I will provide a concise and accurate definition of LangChain.\n",
      "\n",
      "Action:\n",
      "```\n",
      "{\n",
      "  \"action\": \"Final Answer\",\n",
      "  \"action_input\": \"LangChain is a framework designed to simplify the development of applications that integrate with large language models (LLMs). It provides tools and abstractions to streamline the process of building, deploying, and managing applications that leverage LLMs for various tasks such as natural language processing, text generation, and more.\"\n",
      "}\n",
      "```\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'what is LangChain?',\n",
       " 'output': 'LangChain is a framework designed to simplify the development of applications that integrate with large language models (LLMs). It provides tools and abstractions to streamline the process of building, deploying, and managing applications that leverage LLMs for various tasks such as natural language processing, text generation, and more.'}"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, create_structured_chat_agent\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "tools = [TavilySearchResults(max_results=1)]\n",
    "# Get the prompt to use - you can modify this!\n",
    "prompt = hub.pull(\"hwchase17/structured-chat-agent\")\n",
    "# Choose the LLM that will drive the agent\n",
    "llm = ChatOpenAI(temperature=0, model=\"gpt-4o\")\n",
    "\n",
    "# Construct the JSON agent\n",
    "agent = create_structured_chat_agent(llm, tools, prompt)\n",
    "# Create an agent executor by passing in the agent and tools\n",
    "agent_executor = AgentExecutor(\n",
    "    agent=agent, tools=tools, verbose=True, handle_parsing_errors=True\n",
    ")\n",
    "agent_executor.invoke({\"input\": \"what is LangChain?\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m```\n",
      "{\n",
      "  \"action\": \"Final Answer\",\n",
      "  \"action_input\": \"Your name is Bob.\"\n",
      "}\n",
      "```\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': \"what's my name? Do not use tools unless you have to\",\n",
       " 'chat_history': [HumanMessage(content='hi! my name is bob'),\n",
       "  AIMessage(content='Hello Bob! How can I assist you today?')],\n",
       " 'output': 'Your name is Bob.'}"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.messages import AIMessage, HumanMessage\n",
    "\n",
    "agent_executor.invoke(\n",
    "    {\n",
    "        \"input\": \"what's my name? Do not use tools unless you have to\",\n",
    "        \"chat_history\": [\n",
    "            HumanMessage(content=\"hi! my name is bob\"),\n",
    "            AIMessage(content=\"Hello Bob! How can I assist you today?\"),\n",
    "        ],\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## JSON Chat Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m```json\n",
      "{\n",
      "    \"action\": \"tavily_search_results_json\",\n",
      "    \"action_input\": \"LangChain\"\n",
      "}\n",
      "```\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://www.langchain.com/', 'content': 'Join Discord\\nContribute on GitHub\\n5.3M\\nMonthly Downloads\\n67k\\nGithub Stars\\n1800+\\nContributors\\n34k+\\nApps Powered\\nReady to build?\\nGo To Docs\\nGo To Docs\\nGo To Docs\\nContact Sales\\nContact Sales\\nContact Sales\\nProducts and use-cases\\nLangChain\\nLangSmith\\nRetrieval\\nAgents\\nInspiration\\nCode\\nGitHub\\nLangChain Hub\\nPython Docs\\nJS/TS Docs\\nSocial\\nTwitter\\nDiscord\\nBlog\\nLinkedIn\\nYouTube\\nTerms of Service\\nSign up for our newsletter\\nProducts and use-cases\\nLangChain\\nLangSmith\\nRetrieval\\nAgents\\nInspiration\\nCode\\nGitHub\\nLangChain Hub\\nPython Docs\\nJS/TS Docs\\nSocial\\nTwitter\\nDiscord\\nBlog\\nLinkedIn\\nYouTube\\nTerms of Service\\nSign up for our newsletter\\nProducts and use-cases\\nLangChain\\nLangSmith\\nRetrieval\\nAgents\\nInspiration\\nCode\\nGitHub\\nLangChain Hub\\nPython Docs\\nJS/TS Docs\\nSocial\\nTwitter\\nDiscord\\nBlog\\nLinkedIn\\nYouTube\\nTerms of Service\\nSign up for our newsletter Chatbots\\nQ&A Over Docs\\nSummarization\\nCopilots\\nWorkflow Automation\\nDocument Analysis\\nCustom Search\\nHarness the power–and wrangle the complexity– of LLMs\\nGet from proof-of-concept to production on one platform\\nRely on a set of tools built especially for non-deterministic models\\nLeverage new cognitive architectures and battle-tested orchestration\\nThanks to our contributors and partners for making LangChain awesome\\nWhen you build with LangChain, you build alongside a community of developers advancing the frontier of what’s possible with LLMs.\\n 🦜🔗 LangChain\\nLangSmith\\nLangServe\\nAgents\\nRetrieval\\nEvaluation\\nBlog\\nDocs\\n🦜🔗 LangChain\\n🦜🔗 LangChain\\nLangChain Expression Language makes it easy to create custom chains.\\n Go To Docs\\nGo To Docs\\nGo To Docs\\nContact Sales\\nglobal corporations, STARTUPS, and TINKERERS build with LangChain\\nglobal corporations, STARTUPS, and TINKERERS build with LangChain\\nglobal corporations, STARTUPS, and TINKERERS build with LangChain\\nA complete set of powerful building blocks\\nA complete set of powerful building blocks\\n Try it out here\\nGet your LLM application from prototype to production\\nGet your LLM application from prototype to production\\nBuild context-aware, reasoning applications with LangChain’s flexible abstractions and AI-first toolkit.\\n'}]\u001b[0m\u001b[32;1m\u001b[1;3m```json\n",
      "{\n",
      "    \"action\": \"Final Answer\",\n",
      "    \"action_input\": \"LangChain is a platform that offers a set of tools for building context-aware, reasoning applications with flexible abstractions and an AI-first toolkit. It provides a LangChain Expression Language for creating custom chains and aims to help users get their large language model (LLM) applications from prototype to production.\"\n",
      "}\n",
      "```\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'what is LangChain?',\n",
       " 'output': 'LangChain is a platform that offers a set of tools for building context-aware, reasoning applications with flexible abstractions and an AI-first toolkit. It provides a LangChain Expression Language for creating custom chains and aims to help users get their large language model (LLM) applications from prototype to production.'}"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, create_json_chat_agent\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "tools = [TavilySearchResults(max_results=1)]\n",
    "# Get the prompt to use - you can modify this!\n",
    "prompt = hub.pull(\"hwchase17/react-chat-json\")\n",
    "# Choose the LLM that will drive the agent\n",
    "llm = ChatOpenAI()\n",
    "\n",
    "# Construct the JSON agent\n",
    "agent = create_json_chat_agent(llm, tools, prompt)\n",
    "# Create an agent executor by passing in the agent and tools\n",
    "agent_executor = AgentExecutor(\n",
    "    agent=agent, tools=tools, verbose=True, handle_parsing_errors=True\n",
    ")\n",
    "agent_executor.invoke({\"input\": \"what is LangChain?\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m```json\n",
      "{\n",
      "    \"action\": \"Final Answer\",\n",
      "    \"action_input\": \"Your name is Bob.\"\n",
      "}\n",
      "```\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': \"what's my name?\",\n",
       " 'chat_history': [HumanMessage(content='hi! my name is bob'),\n",
       "  AIMessage(content='Hello Bob! How can I assist you today?')],\n",
       " 'output': 'Your name is Bob.'}"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.messages import AIMessage, HumanMessage\n",
    "\n",
    "agent_executor.invoke(\n",
    "    {\n",
    "        \"input\": \"what's my name?\",\n",
    "        \"chat_history\": [\n",
    "            HumanMessage(content=\"hi! my name is bob\"),\n",
    "            AIMessage(content=\"Hello Bob! How can I assist you today?\"),\n",
    "        ],\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## XML Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m<tool>tavily_search_results_json</tool><tool_input>what is LangChain?\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://python.langchain.com/v0.2/docs/introduction/', 'content': \"Introduction. LangChain is a framework for developing applications powered by large language models (LLMs).. LangChain simplifies every stage of the LLM application lifecycle: Development: Build your applications using LangChain's open-source building blocks, components, and third-party integrations.Use LangGraph to build stateful agents with first-class streaming and human-in-the-loop support.\"}]\u001b[0m\u001b[32;1m\u001b[1;3m<final_answer>LangChain is a framework for developing applications powered by large language models (LLMs). It simplifies every stage of the LLM application lifecycle, allowing developers to build applications using open-source building blocks, components, and third-party integrations. LangChain also includes tools like LangGraph for creating stateful agents with support for streaming and human-in-the-loop interactions.</final_answer>\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'what is LangChain?',\n",
       " 'output': 'LangChain is a framework for developing applications powered by large language models (LLMs). It simplifies every stage of the LLM application lifecycle, allowing developers to build applications using open-source building blocks, components, and third-party integrations. LangChain also includes tools like LangGraph for creating stateful agents with support for streaming and human-in-the-loop interactions.'}"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, create_xml_agent\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "\n",
    "tools = [TavilySearchResults(max_results=1)]\n",
    "# Get the prompt to use - you can modify this!\n",
    "prompt = hub.pull(\"hwchase17/xml-agent-convo\")\n",
    "# Choose the LLM that will drive the agent\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# Construct the XML agent\n",
    "agent = create_xml_agent(llm, tools, prompt)\n",
    "# Create an agent executor by passing in the agent and tools\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)\n",
    "agent_executor.invoke({\"input\": \"what is LangChain?\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## OpenAI functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `tavily_search_results_json` with `{'query': 'LangChain'}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://www.langchain.com/', 'content': 'Join Discord\\nContribute on GitHub\\n5.3M\\nMonthly Downloads\\n67k\\nGithub Stars\\n1800+\\nContributors\\n34k+\\nApps Powered\\nReady to build?\\nGo To Docs\\nGo To Docs\\nGo To Docs\\nContact Sales\\nContact Sales\\nContact Sales\\nProducts and use-cases\\nLangChain\\nLangSmith\\nRetrieval\\nAgents\\nInspiration\\nCode\\nGitHub\\nLangChain Hub\\nPython Docs\\nJS/TS Docs\\nSocial\\nTwitter\\nDiscord\\nBlog\\nLinkedIn\\nYouTube\\nTerms of Service\\nSign up for our newsletter\\nProducts and use-cases\\nLangChain\\nLangSmith\\nRetrieval\\nAgents\\nInspiration\\nCode\\nGitHub\\nLangChain Hub\\nPython Docs\\nJS/TS Docs\\nSocial\\nTwitter\\nDiscord\\nBlog\\nLinkedIn\\nYouTube\\nTerms of Service\\nSign up for our newsletter\\nProducts and use-cases\\nLangChain\\nLangSmith\\nRetrieval\\nAgents\\nInspiration\\nCode\\nGitHub\\nLangChain Hub\\nPython Docs\\nJS/TS Docs\\nSocial\\nTwitter\\nDiscord\\nBlog\\nLinkedIn\\nYouTube\\nTerms of Service\\nSign up for our newsletter Chatbots\\nQ&A Over Docs\\nSummarization\\nCopilots\\nWorkflow Automation\\nDocument Analysis\\nCustom Search\\nHarness the power–and wrangle the complexity– of LLMs\\nGet from proof-of-concept to production on one platform\\nRely on a set of tools built especially for non-deterministic models\\nLeverage new cognitive architectures and battle-tested orchestration\\nThanks to our contributors and partners for making LangChain awesome\\nWhen you build with LangChain, you build alongside a community of developers advancing the frontier of what’s possible with LLMs.\\n 🦜🔗 LangChain\\nLangSmith\\nLangServe\\nAgents\\nRetrieval\\nEvaluation\\nBlog\\nDocs\\n🦜🔗 LangChain\\n🦜🔗 LangChain\\nLangChain Expression Language makes it easy to create custom chains.\\n Go To Docs\\nGo To Docs\\nGo To Docs\\nContact Sales\\nglobal corporations, STARTUPS, and TINKERERS build with LangChain\\nglobal corporations, STARTUPS, and TINKERERS build with LangChain\\nglobal corporations, STARTUPS, and TINKERERS build with LangChain\\nA complete set of powerful building blocks\\nA complete set of powerful building blocks\\n Try it out here\\nGet your LLM application from prototype to production\\nGet your LLM application from prototype to production\\nBuild context-aware, reasoning applications with LangChain’s flexible abstractions and AI-first toolkit.\\n'}]\u001b[0m\u001b[32;1m\u001b[1;3mLangChain is a platform that provides a complete set of powerful building blocks for building context-aware, reasoning applications with flexible abstractions and an AI-first toolkit. It offers tools for harnessing the power of language models (LLMs) and provides support for non-deterministic models. LangChain is used by global corporations, startups, and developers to build custom chains and applications. You can learn more about LangChain at their website [here](https://www.langchain.com/).\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'what is LangChain?',\n",
       " 'output': 'LangChain is a platform that provides a complete set of powerful building blocks for building context-aware, reasoning applications with flexible abstractions and an AI-first toolkit. It offers tools for harnessing the power of language models (LLMs) and provides support for non-deterministic models. LangChain is used by global corporations, startups, and developers to build custom chains and applications. You can learn more about LangChain at their website [here](https://www.langchain.com/).'}"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, create_openai_functions_agent\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "tools = [TavilySearchResults(max_results=1)]\n",
    "# Get the prompt to use - you can modify this!\n",
    "prompt = hub.pull(\"hwchase17/openai-functions-agent\")\n",
    "# Choose the LLM that will drive the agent\n",
    "llm = ChatOpenAI(model=\"gpt-3.5-turbo-1106\")\n",
    "\n",
    "# Construct the OpenAI Functions agent\n",
    "agent = create_openai_functions_agent(llm, tools, prompt)\n",
    "# Create an agent executor by passing in the agent and tools\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)\n",
    "agent_executor.invoke({\"input\": \"what is LangChain?\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## OpenAI tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `tavily_search_results_json` with `{'query': 'LangChain'}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://machinelearningmastery.com/understanding-langchain-llm-output-parser/', 'content': 'In this article, we have learned about the LangChain Output Parser, which standardizes the generated text from LLM. We can use the Pydantic Parser to structure the LLM output and provide the result you want. There are many other Output Parsers from LangChain that could be suitable for your situation, such as the CSV parser and the Datetime parser.'}]\u001b[0m\u001b[32;1m\u001b[1;3mLangChain is associated with the LangChain Output Parser, which standardizes the generated text from LLM (Language Model). The LangChain Output Parser uses the Pydantic Parser to structure the LLM output and provide the desired result. Additionally, LangChain offers other Output Parsers, such as the CSV parser and the Datetime parser, which may be suitable for different situations. If you would like to learn more, you can visit the following link: [Understanding LangChain LLM Output Parser](https://machinelearningmastery.com/understanding-langchain-llm-output-parser/)\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'what is LangChain?',\n",
       " 'output': 'LangChain is associated with the LangChain Output Parser, which standardizes the generated text from LLM (Language Model). The LangChain Output Parser uses the Pydantic Parser to structure the LLM output and provide the desired result. Additionally, LangChain offers other Output Parsers, such as the CSV parser and the Datetime parser, which may be suitable for different situations. If you would like to learn more, you can visit the following link: [Understanding LangChain LLM Output Parser](https://machinelearningmastery.com/understanding-langchain-llm-output-parser/)'}"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, create_openai_tools_agent\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "tools = [TavilySearchResults(max_results=1)]\n",
    "# Get the prompt to use - you can modify this!\n",
    "prompt = hub.pull(\"hwchase17/openai-tools-agent\")\n",
    "# Choose the LLM that will drive the agent\n",
    "# Only certain models support this\n",
    "llm = ChatOpenAI(model=\"gpt-3.5-turbo-1106\", temperature=0)\n",
    "\n",
    "# Construct the OpenAI Tools agent\n",
    "agent = create_openai_tools_agent(llm, tools, prompt)\n",
    "\n",
    "# Create an agent executor by passing in the agent and tools\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)\n",
    "\n",
    "agent_executor.invoke({\"input\": \"what is LangChain?\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Tool calling agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `tavily_search_results_json` with `{'query': 'LangChain'}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://www.langchain.com/', 'content': 'Join Discord\\nContribute on GitHub\\n5.3M\\nMonthly Downloads\\n67k\\nGithub Stars\\n1800+\\nContributors\\n34k+\\nApps Powered\\nReady to build?\\nGo To Docs\\nGo To Docs\\nGo To Docs\\nContact Sales\\nContact Sales\\nContact Sales\\nProducts and use-cases\\nLangChain\\nLangSmith\\nRetrieval\\nAgents\\nInspiration\\nCode\\nGitHub\\nLangChain Hub\\nPython Docs\\nJS/TS Docs\\nSocial\\nTwitter\\nDiscord\\nBlog\\nLinkedIn\\nYouTube\\nTerms of Service\\nSign up for our newsletter\\nProducts and use-cases\\nLangChain\\nLangSmith\\nRetrieval\\nAgents\\nInspiration\\nCode\\nGitHub\\nLangChain Hub\\nPython Docs\\nJS/TS Docs\\nSocial\\nTwitter\\nDiscord\\nBlog\\nLinkedIn\\nYouTube\\nTerms of Service\\nSign up for our newsletter\\nProducts and use-cases\\nLangChain\\nLangSmith\\nRetrieval\\nAgents\\nInspiration\\nCode\\nGitHub\\nLangChain Hub\\nPython Docs\\nJS/TS Docs\\nSocial\\nTwitter\\nDiscord\\nBlog\\nLinkedIn\\nYouTube\\nTerms of Service\\nSign up for our newsletter Chatbots\\nQ&A Over Docs\\nSummarization\\nCopilots\\nWorkflow Automation\\nDocument Analysis\\nCustom Search\\nHarness the power–and wrangle the complexity– of LLMs\\nGet from proof-of-concept to production on one platform\\nRely on a set of tools built especially for non-deterministic models\\nLeverage new cognitive architectures and battle-tested orchestration\\nThanks to our contributors and partners for making LangChain awesome\\nWhen you build with LangChain, you build alongside a community of developers advancing the frontier of what’s possible with LLMs.\\n 🦜🔗 LangChain\\nLangSmith\\nLangServe\\nAgents\\nRetrieval\\nEvaluation\\nBlog\\nDocs\\n🦜🔗 LangChain\\n🦜🔗 LangChain\\nLangChain Expression Language makes it easy to create custom chains.\\n Go To Docs\\nGo To Docs\\nGo To Docs\\nContact Sales\\nglobal corporations, STARTUPS, and TINKERERS build with LangChain\\nglobal corporations, STARTUPS, and TINKERERS build with LangChain\\nglobal corporations, STARTUPS, and TINKERERS build with LangChain\\nA complete set of powerful building blocks\\nA complete set of powerful building blocks\\n Try it out here\\nGet your LLM application from prototype to production\\nGet your LLM application from prototype to production\\nBuild context-aware, reasoning applications with LangChain’s flexible abstractions and AI-first toolkit.\\n'}]\u001b[0m\u001b[32;1m\u001b[1;3mLangChain is a platform that offers a complete set of powerful building blocks for building context-aware, reasoning applications with flexible abstractions and an AI-first toolkit. It provides tools for harnessing the power of Large Language Models (LLMs) and navigating the complexity associated with them. LangChain's LangChain Expression Language makes it easy to create custom chains for various applications. The platform is used by global corporations, startups, and tinkerers to build advanced applications. You can find more information on their website: [LangChain Website](https://www.langchain.com/).\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'what is LangChain?',\n",
       " 'output': \"LangChain is a platform that offers a complete set of powerful building blocks for building context-aware, reasoning applications with flexible abstractions and an AI-first toolkit. It provides tools for harnessing the power of Large Language Models (LLMs) and navigating the complexity associated with them. LangChain's LangChain Expression Language makes it easy to create custom chains for various applications. The platform is used by global corporations, startups, and tinkerers to build advanced applications. You can find more information on their website: [LangChain Website](https://www.langchain.com/).\"}"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "from langchain.agents import AgentExecutor, create_tool_calling_agent\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "tools = [TavilySearchResults(max_results=1)]\n",
    "\n",
    "llm = ChatOpenAI(model=\"gpt-3.5-turbo-0125\")\n",
    "prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\n",
    "            \"system\",\n",
    "            \"You are a helpful assistant. Make sure to use the tavily_search_results_json tool for information.\",\n",
    "        ),\n",
    "        (\"placeholder\", \"{chat_history}\"),\n",
    "        (\"human\", \"{input}\"),\n",
    "        (\"placeholder\", \"{agent_scratchpad}\"),\n",
    "    ]\n",
    ")\n",
    "\n",
    "# Construct the Tools agent\n",
    "agent = create_tool_calling_agent(llm, tools, prompt)\n",
    "\n",
    "# Create an agent executor by passing in the agent and tools\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)\n",
    "agent_executor.invoke({\"input\": \"what is LangChain?\"})"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langchain0_1",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
